import json

from django.http import JsonResponse, HttpResponse

import jwt
import datetime

from app.forms import LoginForm
from app.models import User


def register(request):
    body = json.loads(request.body.decode('utf-8'))

    email = body.get('email')
    username = body.get('username')
    password = body.get('password')
    password1 = body.get('password1')

    if request.method == 'POST':
        if password != password1:
            return JsonResponse({"data": "两次密码不一致"})
        stu1 = User.objects.filter(email=email).first()

        if stu1:
            return JsonResponse({"data": "该邮箱已经注册过，建议前往找回密码"})

        dic = {
            'exp': datetime.datetime.now() + datetime.timedelta(days=1),  # 过期时间
            'iat': datetime.datetime.now(),  # 开始时间
            'iss': 'weixijin',  # 签名
            'data': {  # 内容，一般存放该用户id和开始时间
                'username': username,
            },
        }

        password = jwt.encode(dic, password, algorithm='HS256')  # 加密生成字符串
        # print(password)

        stu = User(username=username, password=password, email=email)
        stu.save()

        return JsonResponse({"msg": "register通过"})


def login(request):
    print("request.body---{}".format(request.body))
    print("request.Post---{}".format(request.POST))
    body = json.loads(request.body.decode('utf-8'))

    username = body.get('username')
    password = body.get('password')
    try:
        stu = User.objects.filter(username=username)
        # oldpassword = stu[0].password
    except:
        return JsonResponse({"data": "没有该用户，前往注册吧"})

    if request.method == 'POST':
        dic = {
            'exp': datetime.datetime.now() + datetime.timedelta(days=1),  # 过期时间
            'iat': datetime.datetime.now(),  # 开始时间
            'iss': 'weixijin',  # 签名
            'data': {  # 内容，一般存放该用户id和开始时间
                'username': username,
            },
        }
        # print(password)
        oldpassword = jwt.encode(dic, password, algorithm='HS256')  # 加密生成字符串
        try:
            s = jwt.decode(oldpassword, password, issuer='weixijin', algorithms=['HS256'])  # 解密，校验签名
            return JsonResponse({"data": "pass"})
        except:
            return JsonResponse({"data": "密码错误"})


def captcha(request):
    # form = LoginForm()
    # print(form)
    return JsonResponse({"data": "ok", "yzm": "form"})
